package com.zkadmin.controller;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Window;
import org.zkoss.zul.event.PagingEvent;
import org.zkoss.zul.event.ZulEvents;

import com.zkadmin.entity.SysResource;
import com.zkadmin.renderer.EditResourceTreeListRenderer;
import com.zkadmin.service.SysResourceService;
import com.zkadmin.util.AdminConstants;

@SuppressWarnings("serial")
public class EditResourceTreeDialogCtrl extends BaseCtrl<Window> {

	@WireVariable
	private SysResourceService sysResourceService;

	@Wire
	private Window win;

	@Wire
	private Listbox resourceLst;

	@Wire
	private Paging resourcePg;

	@Override
	protected void init(Window win) {
		this.win = win;
		resourceLst.setItemRenderer(new EditResourceTreeListRenderer(win, this, sysResourceService));
		refreshData();
		
		resourcePg.addEventListener(ZulEvents.ON_PAGING, new EventListener<PagingEvent>() {
			@Override
			public void onEvent(PagingEvent event) throws Exception {
				resourcePg.setActivePage(event.getActivePage());
				refreshData();
			}
		});
	}

	public void refreshData() {
		Pageable pageable = new PageRequest(resourcePg.getActivePage(), resourcePg.getPageSize());
		Page<SysResource> page = sysResourceService.findGrouped(pageable);
		resourceLst.setModel(new ListModelList<SysResource>(page.getContent()));
		resourcePg.setTotalSize((int)page.getTotalElements());
	}

	@Listen("onClose=window")
	public void closeDialog(Event e) {
		Events.postEvent(AdminConstants.EVENT_ONREFRESH, win, null);
		win.onClose();
	}

}
